package org.adw.launcher2.ld.secret.db;

import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.adw.launcher2.ld.secret.dom.MyVideo;
import org.adw.launcher2.ld.secret.ui.utils.Global;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.MediaStore;
import android.util.Log;

public class MyVideoCache {
	private static String TABLE_MY_VIDEO = "my_video";
	private static MyVideoCache instance = null;
	private SQLiteDatabase db;
	public static MyVideoCache getInstance(DatabaseHelper dbHelper) {
		if (instance == null) {
			instance = new MyVideoCache(dbHelper);
			
		}
		return instance;
	}

	private MyVideoCache(DatabaseHelper dbHelper) {
		db = dbHelper.db;
		onCreateTable();
	}

	private void onCreateTable() {
		db.execSQL("CREATE TABLE IF NOT EXISTS my_video(id  INTEGER PRIMARY KEY NOT NULL  UNIQUE, image BLOB, "
						+ "absolute_path_no_extend TEXT,extend TEXT );");
	}

	public void insertVideoToDb(ContentValues values) {
		db.insert(TABLE_MY_VIDEO, null, values);

	}

	public void insertVideoToMemory(MyVideo myVideo) {
		// luc nay trong memory (external) chua file myvideo.abc
		// bay gio ta se rename lai
		String videoLocationInMemory = myVideo.getAbsolutePathNoExtend()
				+ ".abc";
		String videoLocation = myVideo.getAbsolutePathNoExtend()
				+ myVideo.getFileExtend();// trong db chua extends cu cua file
											// video
		Log.d("insertVideoToMemory:videoLocation", videoLocation);
		File fileLocationInMemory = new File(videoLocationInMemory);
		File fileLocation = new File(videoLocation);
		boolean isSuccess = fileLocationInMemory.renameTo(fileLocation);
		Log.d("MyVideoCache:isRename", isSuccess + "");
		Log.d("fileLocation.toString", fileLocation.toString());
		Log.d("fileLocationInMemory.toString", fileLocationInMemory.toString());
	}

	public void deleteVideoFromDb(long id) {
		Log.d("deleteVideoFromDbStart", id + "");
		db.delete(TABLE_MY_VIDEO, " id = ? ", new String[] { id + "" });
		Log.d("deleteVideoFromDbEnd", id + "");
	}

	public void deleteVideoFromMemory(long id, Bitmap image, String absolutePath, String fileExtend) {
		File fileLocationInMemory = new File(absolutePath + fileExtend);
		Log.d("fileLocationInMemory", fileLocationInMemory.getAbsolutePath());
		File fileLocationInDb = new File(absolutePath+ ".abc");
		Log.d("fileLocationInDb", fileLocationInDb.getAbsolutePath());
		boolean isMoveSuccess = fileLocationInMemory.renameTo(fileLocationInDb);
		Log.d("MyVideoCache:isMoveSuccess", isMoveSuccess + "");
		int rowDeleted = Global.cr.delete(
				MediaStore.Video.Media.EXTERNAL_CONTENT_URI, "_id = ? ",
				new String[] { id + "" });
		int row1Deleted = Global.cr.delete(
				MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI, "_id = ? ",
				new String[] { id+ "" });
		Log.d("deleteVideoFromMemory", rowDeleted + " " + row1Deleted);
	}

	public List<MyVideo> getVideosNoImageFromMemory(ContentResolver cr) {
		List<MyVideo> listVideo = new LinkedList<MyVideo>();
		String[] proj = { MediaStore.Video.Media._ID,
				MediaStore.Video.Media.DATA };
		Cursor cursor = cr.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
				proj, null, null, null);

		while (cursor.moveToNext()) {
			int id = cursor.getInt(cursor
					.getColumnIndex(MediaStore.Video.Media._ID));
			String filename = cursor.getString(cursor
					.getColumnIndex(MediaStore.Video.Media.DATA));
//			Bitmap image = MediaStore.Video.Thumbnails.getThumbnail(cr, id,
//					MediaStore.Video.Thumbnails.MICRO_KIND, null);
			
			Log.d("filename", filename);
			String[] filterFileName = filename.split("/");
			String absolute_path_no_extend = filename.substring(0, filename
					.length() - 4);
			Log.d("absolute_path", absolute_path_no_extend);
			String fileNameWithExtention = filterFileName[filterFileName.length - 1];
			String fileExtend = fileNameWithExtention.substring(
					fileNameWithExtention.length() - 4, fileNameWithExtention
							.length());
			MyVideo myVideo = new MyVideo(id, null, absolute_path_no_extend,
					fileExtend);
			listVideo.add(myVideo);
		}
		cursor.close();
		return listVideo;
	}
	public HashMap<String, Bitmap> getImageOfVideo(ContentResolver cr){
		HashMap<String, Bitmap> images = new HashMap<String, Bitmap>();
		String[] proj = { MediaStore.Video.Media._ID,
				MediaStore.Video.Media.DATA };
		Cursor cursor = cr.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
				proj, null, null, null);
		while(cursor.moveToNext()){
			int id = cursor.getInt(cursor
					.getColumnIndex(MediaStore.Video.Media._ID));
			Bitmap image = MediaStore.Video.Thumbnails.getThumbnail(cr, id,
			MediaStore.Video.Thumbnails.MICRO_KIND, null);
			images.put(id+"", image);
			
		}
		cursor.close();
		return images;
	}
	
	public Bitmap getImageOfVideoFromMemory(ContentResolver cr, String userId){
		Bitmap image = null;
		String[] proj = { MediaStore.Video.Media._ID,
				MediaStore.Video.Media.DATA };
		Cursor cursor = cr.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
				proj, null, null, null);
		if(cursor.moveToFirst()){
			image = null;
			image = MediaStore.Video.Thumbnails.getThumbnail(cr,Long.parseLong(userId),MediaStore.Video.Thumbnails.MICRO_KIND, null);
		
		}
		cursor.close();
		return image;
	}

	public static MyVideo getVideoFromMemory(ContentResolver cr, long id) {
		MyVideo myVideo = null;
		Cursor cursor = cr.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
				null, MediaStore.Video.Media._ID + " = ? ", new String[] { id
						+ "" }, null);

		if (cursor.moveToFirst()) {
			String filename = cursor.getString(cursor
					.getColumnIndex(MediaStore.Video.Media.DATA));
			Bitmap image = MediaStore.Video.Thumbnails.getThumbnail(cr, id,
					MediaStore.Video.Thumbnails.MINI_KIND, null);
			Log.d("filename", filename);
			String[] filterFileName = filename.split("/");
			String absolute_path_no_extend = filename.substring(0, filename
					.length() - 4);
			Log.d("absolute_path", absolute_path_no_extend);
			String fileNameWithExtention = filterFileName[filterFileName.length - 1];
			String fileExtend = fileNameWithExtention.substring(
					fileNameWithExtention.length() - 4, fileNameWithExtention
							.length());
			myVideo = new MyVideo(id, image, absolute_path_no_extend,
					fileExtend);
		}
		cursor.close();
		return myVideo;
	}

	public List<MyVideo> getVideosNoImageFromDb() {
		List<MyVideo> listVideo = new LinkedList<MyVideo>();
//		Bitmap image ;
		Cursor cursor = db.rawQuery("SELECT * FROM my_video ", null);
		while (cursor.moveToNext()) {
//			image = null;
			long id = cursor.getLong(cursor.getColumnIndex("id"));
			String absolutePathNoExtend = cursor.getString(cursor
					.getColumnIndex("absolute_path_no_extend"));
			String extend = cursor.getString(cursor.getColumnIndex("extend"));
//			byte[] bb = cursor.getBlob(cursor.getColumnIndex("image"));
//			if(bb!=null){
//					image = BitmapFactory.decodeByteArray(bb, 0, bb.length);
//			}
			listVideo.add(new MyVideo(id, null, absolutePathNoExtend, extend));
		}
		cursor.close();
		return listVideo;
	}
	public Bitmap getImageOfVideosFromDb(String userId) {
		Bitmap image = null ;
		Cursor cursor = db.rawQuery("SELECT * FROM my_video WHERE id = " + Long.parseLong(userId), null);
		
		if (cursor.moveToFirst()) {
			
			image = null;
			byte[] bb = null;
			bb = cursor.getBlob(cursor.getColumnIndex("image"));
			if(bb!=null){
					image = BitmapFactory.decodeByteArray(bb, 0, bb.length);
			}
			
		}
		cursor.close();
		return image;
	}
	public Bitmap getImageOfPhotoFromMemory(ContentResolver cr, String userId){
		Bitmap image = null;
		String[] proj = { MediaStore.Images.Media._ID,
				MediaStore.Images.Media.DATA };
		Cursor cursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				proj, null, null, null);
		if(cursor.moveToFirst()){
			image = null;
			image = MediaStore.Images.Thumbnails.getThumbnail(cr,Long.parseLong(userId),MediaStore.Images.Thumbnails.MICRO_KIND, null);
		
		}
		cursor.close();
		return image;
	}
	

}
